//if (window.plus) {
//    mylifePageReady();
//} else {
//    document.addEventListener('plusready', mylifePageReady, false);
//}
$(function () {
    if (AGENT_CLIENT.WEB) {
        mylifePageReady();
    }
})
var _mylifePage = null;
// 初始化方法
function mylifePageReady() {
		$.getScript("http://pv.sohu.com/cityjson?ie=utf-8").fail(function (res) {
			$.toast(ERROR_MESSAGE.network);
		});
    var defaultdata = {
        'focus_goods': 0,
        'focus_shop': 0,
        'orders': 0,
        'pending_orders': 0,
        'non_payment': 0,
        'unread_messages': 0,
        'non_pay': 0,
        'non_send': 0,
        'non_receive': 0,
        'non_comment': 0,
        'non_return': 0,
        'nickname': '',
        'avatar': '',
        'coin': 0,
        'frozen_coin': 0,
        'money': 0,
        'frozen_money': 0,
        'cash': 0,
        'frozen_cash': 0,
        'member_id': 0
    };
    var _currentloginuser = null;
    var mylifePage = function () {
        this.init();
    };
    mylifePage.prototype = {
        // 初始化
        init: function () {
            this.loadData();
            this.bindEvent();
        },
        //加载数据
        loadData: function (isrefresh) {
            var thisPage = this;
            _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
            if (!_currentloginuser) {
                this.paintPage(defaultdata);
                return;
            }

            $.ajax({
                headers: {
                    "token": _currentloginuser.token
                },
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/member/" + _currentloginuser.id
            }).done(function (data) {
                setLocalStorage(STORAGE_MANAGER.currentmember, data);
                if (!isrefresh) {
                    thisPage.paintPage(data);
                    thisPage.setMessageCount();
                } else {
                    thisPage.setMessageCount();
                }
            }).fail(function (res) {
                thisPage.paintPage(defaultdata);
                var response = JSON.parse(res.responseText);
                if (response.message && response.message.indexOf("票据") > -1) {
                    $.alert("你的帐号已经在其他地方登录", function () {
                        clearLocalStorage();
                        // 设置IOS顶部样式
                        if (AGENT_CLIENT.APP && os.ios) {
                            plus.navigator.setStatusBarBackground("#FEFEFE");
                            plus.navigator.setStatusBarStyle('UIStatusBarStyleDefault');
                        }
                        redirect("../account/login.html");
                        return;
                    });
                }else{
                	$.toast(ERROR_MESSAGE.network);
                }
            });
        },
        // 画页面
        paintPage: function (data) {
            var html = [],
                src = '';
            //头像
            if (data && data.member_id > 0) {
                // 更新用户缓存
                _currentloginuser["coin"] = data.coin;
                setLocalStorage(STORAGE_MANAGER.user, _currentloginuser);
                html.push('<div class="wdshtbbg">');
                html.push('<div class="dptxbg">');
                if (data.avatar) {
                    src = getImageUrl(data.avatar, 200, 200);
                } else {
                    src = "../../images/avatar-male.png";
                }
                html.push('<p name="pageitem" tip="../account/account.html" class="dptxtu" style="text-align:center;width:90px;height:90px;"><img src="' + src + '" style="width:90px;height:90px;z-index:10;"/></p>');
                html.push('<p name="pageitem" tip="../account/barcode.html" class="dpmingche"><span>' + data.nickname + '</span>');
                html.push('<i class="iconfont icon-erweima"></i>');
                html.push('</p>');
                html.push('</div>');
                html.push('</div>');
            } else {
                html.push('<div class="wdshtbbg">');
                html.push('<div class="dptxbg">');
                html.push('<p style="text-align:center;width:90px;height:90px;" name="pageitem" class="dptxtu"  tip="../mine/mylife.html"><span class="wdshwdltx"><img src="../../images/wdltx.png"/><br>登录/注册</span></p>');
                html.push('<p  class="dpmingche huangse">欢迎来到如此生活</p>');
                html.push('</div>');
                html.push('</div>');
            }
            html.push("<div style='background: #eee'>")
            //钱包和关注
            html.push('<div class="muokuaibg mbtopbottom mtop300" style="background:#fff">');
            html.push('<div class="height mbbottom"></div>');
            html.push('<div class="mkyis mbbottom">');
            html.push('<p class="wdshxj mbright hover-style" style="border: 1px solid #eee;">');
            html.push('现金金额:  <b>' + data.cash + '</b><br><em>冻结：' + data.frozen_cash + '</em>');
            html.push('</p>');
            html.push('<p class="wdshxj1">');
            html.push('<span class="mbbottom hover-style">我的钱包:  <b>' + data.money + '</b><em>冻结：' + data.frozen_money + '</em></span>');
            html.push('<span class="hover-style">我的星币:  <b>' + data.coin + '</b><em>冻结：' + data.frozen_coin + '</em></span>');
            html.push('</p>');
            html.push('</div>');
            html.push('<div class="mkyix">');
            html.push('<p name="pageitem" tip="../mine/attention.html?type=goods" class="wdsbbb mbright hover-style"><b>' + data.focus_goods + '</b><br>关注的宝贝</p>');
            html.push('<p name="pageitem" tip="../mine/attention.html?type=shop" class="wdsbbb mbright hover-style"><b>' + data.focus_shop + '</b><br>关注的店铺</p>');
            html.push('<p name="pageitem"  tip="../mine/attention.html?type=trace" class="wdsbbb hover-style"><b>' + data.focus_goods + '</b><br>我的足迹</p>');
            html.push('</div>');
            html.push('</div>');
            //订单分类个数
            //data.status = 200,data.non_payment=2,data.pending_orders=1;
            html.push('<div class="navbg mbtopbottom">');
            html.push('<h2 name="pageitem" tip="../order/orders.html"  class="mkbiaoti mbbottom">');
            html.push('<em class="wdshtb"><b><img src="../../images/wdshtb1.png"></b>我的订单</em>');
            html.push('<span class="wdshyb"><i class="iconfont icon-jiantou2"></i><i class="huizi">查看全部已购买订单</i></span>');
            html.push('</h2>');
            html.push('<ul class="nav nav-tubiao">');
            //待付款
            html.push('<li name="pageitem" tip="../order/orders.html?type=unpay">');
            html.push('<p class="dfhsl" id="non_payment">' + data.non_pay + '</p>');
            html.push('<i class="iconfont icon-youhuiquan"></i><span>待付款</span></li>');
            //待发货
            html.push('<li name="pageitem" tip="../order/orders.html?type=pay">');
            html.push('<p class="dfhsl" id="non_send">' + data.non_send + '</p>');
            html.push('<i class="iconfont icon-wuliu"></i><span>待发货</span></li>')
            //待评价
            html.push('<li  name="pageitem"  tip="../order/orders.html?type=finish">');
            html.push('<p class="dfhsl" id="pending_orders">' + data.pending_orders + '</p>');
            html.push('<i class="iconfont icon-daipingjia"></i><span>待评价</span></li>');
            //退款售后
            html.push('<li name="pageitem"  tip="../order/aftersaleorders.html?status=all">');
            html.push('<p class="dfhsl" id="non_return">' + data.non_return + '</p>');
            html.push('<i class="iconfont icon-gouwu"></i><span>退款/售后</span></li>');
            html.push('</ul>');
            html.push('</div>');
            //我的如此生活
            html.push('<div class="navbg mbtopbottom">');
            html.push('<h2 class="mkbiaoti_noactive mbbottom">');
            html.push('<em class="wdshtb"><b><img src="../../images/wdshtb2.png"></b>我的如此生活</em>');
            //          html.push('<span class="wdshyb"><i class="huizi"></i><a href="javascript:void(0);"></a></span>');
            html.push('</h2>');
            html.push('<ul class="nav nav-tubiao">');
            html.push('<li name="pageitem"tip="../coin/coinlist.html"><i class="iconfont icon-xingxing"></i><span>领星币</span></li>');
            html.push('<li name="pageitem" tip="../mine/show.html"><i class="iconfont icon-xiangji"></i><span>我的星粉秀</span></li>');
            html.push('<li name="pageitem" tip="../mine/coupon.html"><i class="iconfont icon-wodeyouhuiquan"></i><span>我的优惠券</span></li>');
            html.push('<li name="pageitem"  tip="../mine/message.html">');
            html.push('<p class="dfhsl" id="unread_messages">' + data.unread_messages + '</p>');
            html.push('<i class="iconfont icon-xiaoxi"></i><span>我的消息</span></a></li>');
            html.push('</ul>');
            html.push('</div>');
            //跳转连接
            html.push('<div class="wdshheng">');
            html.push('<p name="pageitem" tip="../mine/invite.html" class="mkbiaoti mbtopbottom  wdshht"><em class="wdshtb"><b><img src="../../images/wdshtb3.png"></b>我的邀请</em><span class="wdshyb"><i class="iconfont icon-jiantou2"></i></span></p>');
            html.push('<p name="pageitem" tip="../mine/income.html" class="mkbiaoti mbtopbottom  wdshht"><em class="wdshtb"><b><img src="../../images/wdshtb4.png"></b>我的收入</em><span class="wdshyb"><i class="iconfont icon-jiantou2"></i></span></p>');
            html.push('<p name="pageitem" tip="../mine/account_safe.html" class="mkbiaoti mbtopbottom  wdshht"><em class="wdshtb"><b><img src="../../images/wdshtb5.png"></b>账户与安全</em><span class="wdshyb"><i class="iconfont icon-jiantou2"></i></span></p>');
            html.push('<p name="pageitem" tip="../mine/feedback.html" class="mkbiaoti mbtopbottom  wdshht" style="margin-bottom: 8px;"><em class="wdshtb"><b><img src="../../images/wdshtb6.png"></b>意见反馈</em><span class="wdshyb"><i class="iconfont icon-jiantou2"></i></span></p>');
            html.push('</div></div>');
            $("#main").html(html.join(''));
        },

        // 设置未读消息
        setMessageCount: function () {
            // 未读短信个数
            var currentMember = getLocalStorage(STORAGE_MANAGER.currentmember);
            if (currentMember.non_pay > 0) {
                $("#non_payment").show().text(currentMember.non_pay);
            }
            if (currentMember.non_send > 0) {
                $("#non_send").show().text(currentMember.non_send);
            }
            if (currentMember.pending_orders > 0) {
                $("#pending_orders").show().text(currentMember.pending_orders);
            }
            if (currentMember.non_return > 0) {
                $("#non_return").show().text(currentMember.non_return);
            }
            if (currentMember.unread_messages > 0) {
                $("#unread_messages").show().text(currentMember.unread_messages);
            }
        },

        //绑定事件
        bindEvent: function () {
            var thisPage = this;
            //下拉时顶部固定
            this.pullDown();
            $("#btmsetting,#showpublish").on("click", function () {
                var url = $(this).attr("tip");
                clickPageItem(url);
            });
            $("#main").on("click", "[name=pageitem]", function () {
                var url = $(this).attr("tip");
                clickPageItem(url);
            });

            function clickPageItem(url) {
                if (!url) {
                    return;
                }
                _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
                // 未登陆
                if (!_currentloginuser) {
                    // 设置IOS顶部样式
                    if (AGENT_CLIENT.APP && os.ios) {
                        plus.navigator.setStatusBarBackground("#FEFEFE");
                        plus.navigator.setStatusBarStyle('UIStatusBarStyleDefault');
                    }
                    redirect("../account/login.html?backurl=" + url.replace("../", "").replace("/", "|"));
                    return;
                }
                // 已登录判断token是否有效
                thisPage.checkToken(url);
            }
        },
        // 下拉
        pullDown: function () {
            if (window.os.android) {
                window.onscroll = function () {
                    var top = $(this).scrollTop();
                    $("#header").css({
                        "background": "rgba(240, 130, 0, " + (top / 90) + ")"
                    });
                }
            } else {
                $("#main").scroll(function () {
                    var top = $(this).scrollTop();
                    $("#header").css({
                        "background": "rgba(240, 130, 0, " + (top / 90) + ")"
                    });
                })
            }
        },
        // 获取登录信息
        checkToken: function (url) {
            if (!_currentloginuser) {
                return;
            }
            $.ajax({
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/account/login/" + _currentloginuser.token
            }).done(function (data) {
                // 设置IOS顶部样式
                if (AGENT_CLIENT.APP && os.ios) {
                    plus.navigator.setStatusBarBackground("#FEFEFE");
                    plus.navigator.setStatusBarStyle('UIStatusBarStyleDefault');
                }
                if ("../coin/coinlist.html" == url && AGENT_CLIENT.APP) {
                    plus.webview.getWebviewById("../home/main.html").evalJS("redirectTab(2)");
                } else {
                    redirect(url);
                }
            }).fail(function (res) {
                if (res) {
                    $.alert("你的帐号已经在其他地方登录", function () {
                        clearLocalStorage();
                        // 设置IOS顶部样式
                        if (AGENT_CLIENT.APP && os.ios) {
                            plus.navigator.setStatusBarBackground("#FEFEFE");
                            plus.navigator.setStatusBarStyle('UIStatusBarStyleDefault');
                        }
                        reloadPage();
                        redirect("../account/login.html?backurl=" + url.replace("../", "").replace("/", "|"));
                        return;
                    });
                } else {
                    $.alert("网络异常");
                }
            });
        }
    }
    _mylifePage = new mylifePage();
}

//  触发当前页
function activePage() {
		$.getScript("http://pv.sohu.com/cityjson?ie=utf-8").fail(function (res) {
			$.toast(ERROR_MESSAGE.network);
		});	
    if (_mylifePage) {
        _mylifePage.loadData(true);
    }

    // 显示新版本提示
    var latestVersion = getLocalStorage(STORAGE_MANAGER.latestversion);
    if (latestVersion && !latestVersion.islatest) {
        $("#newVersionTip").show();
    } else {
        $("#newVersionTip").hide();
    }
}

// 重新加载页面
function reloadPage() {
    if (_mylifePage) {
//      plus.navigator.setStatusBarBackground("#f08200");
//      plus.navigator.setStatusBarStyle('UIStatusBarStyleBlackOpaque');    	
        _mylifePage.loadData();
    }
}

// 更新我的消息
function refeshMsgCount() {
    var oricount = parseInt($("#unread_messages").text());
    if (oricount >= 1) {
        oricount = oricount - 1;
    }
    if (oricount < 1) {
        $("#unread_messages").hide().text(oricount);
    } else {
        $("#unread_messages").text(oricount);
    }
}